/**
 * ajax操作
 * @param {object} request 请求对象
 * @param {string} request.url 请求地址
 * @param {string} [request.data] 发送数据
 * @param {string} [request.method = "get"] 请求方式，get | post
 */
class Ajax {
    constructor(request, callback) {
        this.request = request;
        this.xhr = new XMLHttpRequest();
        this.xhr.onreadystatechange = () => {
            if (this.xhr.readyState == 4) {
                if (this.xhr.status < 400) {
                    callback(null, this.xhr.responseText, this.xhr);
                }
                else {
                    callback(`通信异常: ${ request.url }\n状态码：${ this.xhr.status }`, this.xhr.responseText, this.xhr);
                }
            }
        }

        this.request.method = request.method || "get";
        this.request.method = request.method.toLowerCase();
        this[request.method]();
    }

    get(data) {
        let list = [];
        for (let key in this.request.data) {
            list.push(`${ encodeURIComponent(key) }=${ encodeURIComponent(this.request.data[key]) }`);
        }
        this.xhr.open("GET", list.length == 0 ? this.request.url : `${ this.request.url }?${ list.join("&") }`, true);
        this.xhr.send(null);
    }

    post() {
        this.xhr.open("POST", this.request.url, true);
        if (this.request.header) {
            for (let key in this.request.header) {
                this.xhr.setRequestHeader(key, this.request.header[key]);
            }
            if (this.request.header["Content-type"] == "application/json") {
                this.request.data = JSON.stringify(this.request.data);
            }
            else {
                let list = [];
                for (let key in request.data) {
                    list.push(`${ encodeURIComponent(key) }=${ encodeURIComponent(request.data[key]) }`);
                }
            }
        }
        else{
            this.xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        }
        this.xhr.send(this.request.data);
    }

    patch() {
        this.xhr.open("PATCH", this.request.url, true);
        if (this.request.header) {
            for (let key in this.request.header) {
                this.xhr.setRequestHeader(key, this.request.header[key]);
            }
            if (this.request.header["Content-type"] == "application/json") {
                this.request.data = JSON.stringify(this.request.data);
            }
            else {
                let list = [];
                for (let key in request.data) {
                    list.push(`${ encodeURIComponent(key) }=${ encodeURIComponent(request.data[key]) }`);
                }
            }
        }
        else{
            this.xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        }
        this.xhr.send(this.request.data);
    }
}